import axios from "./axios.config"

// 引入qs模块，用来序列化post类型的数据，后面会提到
import QS from 'qs'

import { uploadUrl } from '../config'

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    })
  })
}

/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function post(url, params) {
  return new Promise((resolve) => {
    axios.post(url, QS.stringify(params))
      .then(res => {
        resolve(res.data)
      })
  })
}

/**
 * put 请求
 * @param {Object} url
 * @param {Object} params
 */
export function put(url, params) {
  return new Promise((resolve) => {
    axios.put(url, QS.stringify(params))
      .then(res => {
        resolve(res.data)
      })
  })
}

/**
 * delete 请求
 * @param {Object} url
 * @param {Object} params
 */
export function del(url, params) {
  return new Promise((resolve) => {
    axios.delete(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    })
  })
}

/**
 * 上传
 * @param {Object} file
 */
export function upload(file, fileGroupId = 0, fileType = "image") {
  return new Promise((resolve, reject) => {
    let formData = new FormData()
    formData.append('file', file)
    let config = {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    }
    axios.post(uploadUrl + '?file_type=' + fileType + '&file_group_id=' + fileGroupId, formData, config)
      .then(res => {
        resolve(res.data)
      }).catch(err => {
        console.log(err);
      })
  })
}